import "../../utils/axios";
import axios from "../../utils/axios";
Page({
  /**
   * 页面的初始数据
   */
  data:{
    tabbar:["个人计划","活动日历"],
    currentindex:0,
    nowyear:new Date().getFullYear(),
    nowmonth:new Date().getMonth(),
    schoolname:"",
    region:['全部校区','大学城','番禺','沙河','龙洞'],
    selectregion:'大学城',
    nowweekday:new Date().getDay(),
    weekday:['日','一','二','三','四','五','六'],
    weekdate:[],
    nowday:new Date().getDate(),
    plans:[],
    daytime:['8:00','10:00','12:00','14:00','16:00','18:00','20:00','22:00'],
    currentcalendar:0,
    calendardates:[],
    calendarmonth:new Date().getMonth(),
    calendaryear:new Date().getFullYear(),
    monthday:new Date(new Date().getFullYear(),new Date().getMonth()+1,1).getTime(),
    monthcalendarmonth:new Date().getMonth(),
    monthcalendaryear:new Date().getFullYear(),
    monthcalendardate:[],
    monthcalendarmonthactive:new Date().getMonth(),
    monthcalendardateactive:new Date().getDate(),
    calendar:[],
    myplan:[],
    plancalendar:[],
    activitycalendar:[],
    planactivities:[],
    myplans:[[],[],[]],
    storeBindings:{},
    todayplantimes:[""],
    weekcalendar:[[],[],[],[],[],[],[]],
    calendartypes:['周历','月历'],
    calendartype:'周历',
    calendarindex:0,
    plantitle:['','今天','明天'],
    activities:[],
    myactivities:[],
    weekactivities:[],
    mymonthactivities:{},
    monthactivities:{},
    isbottom:false,
    colors:["blue","yellow","lightblue"],
    colorindex:0,
    monthcalendaractivities:[]
  },
  async onLoad(){
},
async init(){
  
  //星期1日期
    var startDate=new Date(new Date().getTime()-new Date().getDay()*1000*60*60*24)
    var weekdates=[]
  //一星期的日期
    for (let i = 0; i < 7; i++) {
   weekdates.push(new Date(startDate.getTime()+24*60*60*1000*i).getDate())
    }
    //每月天数
    var monthday=new Date(this.data.monthday-24*60*60*1000).getDate()
    this.setData({
      weekdate:weekdates,
      monthday:monthday,
      calendardates:weekdates
    })
    //周历活动和课程安排   
},
async getnowweekactivity(){
  var user=getApp().globalData.user
  this.setData({
    schoolname:user.school
  })
  var starttimestr=new Date().getFullYear()+"-"+new Date().getMonth()+"-"+this.data.weekdate[0]+" 00:00:00"
      var endtimestr=new Date().getFullYear()+"-"+new Date().getMonth()+"-"+this.data.weekdate[6]+" 24:00:00"
      var weekcalendar=[[],[],[],[],[],[],[]]
      var result=await axios.get('/activity?flag=1&verified=1&school='+user.school+"&start="+starttimestr+"&end="+endtimestr+"&campus="+this.data.selectregion)
      var activities=result
      //获取课程表数据
      //TODO
      this.setData({
        weekcalendar:weekcalendar
      })
},
async getplanactivity(){
  await this.getmyplan()
  await this.getmyactivity()
  var startdate=new Date(new Date().getTime()-(new Date().getDay())*24*60*60*1000)
  console.log(startdate)
var planactivities=[]
  for (let i = 0; i < 7; i++) {
    var planactivityitems=[] 
    var starttime=new Date(startdate.getFullYear(),startdate.getMonth(),startdate.getDate()+i,8,0,0).getTime() 
    for (let j = 0; j < 7; j++) {
        starttime+=j*60*60*1000
        var planactivityitem=[]
        for (let k = 0; k < this.data.plancalendar.length; k++) {
          const item = this.data.plancalendar[k];
          if(item.ts-starttime>=0&&item.ts-starttime-2*60*60*1000<=0){
            planactivityitem[0]=true
            break
          }
        }
        for (let k = 0; k < this.data.activitycalendar.length; k++) {
          const item = this.data.activitycalendar[k];
          if(item.start-starttime>=0&&item.start-starttime-2*60*60*1000<=0){
            planactivityitem[1]=true
            break
          }
        }
        planactivityitems.push(planactivityitem)
    }
    planactivities.push(planactivityitems)
  }
  console.log(planactivities)
  this.setData({
    planactivities:planactivities
  })
  await console.log(this.data.activitycalendar)
  await console.log(this.data.plancalendar)
},
async getmyplan(){
 var myplan=await axios.get('/plan')
  console.log(myplan)
        var topplans=[]
        var todayplans=[]
        var tomorrowplans=[];
          for (let index = 0; index < myplan.length; index++) {
            const item = myplan[index];
            switch(item.mode){
              case "娱乐": item.color="#FCD25E"
              break
              case "交友": item.color="#7084F2"
              break
              case "学习": item.color="#50D7E9"
              break
            }
          var datetime=new Date(item.ts)
          var hour=datetime.getHours()
          var minute=datetime.getMinutes()
          var second=datetime.getSeconds()
        item.datetime=hour+":"+minute+":"+second
         var now=new Date()
              var nowtime=new Date(now.getFullYear(),now.getMonth(),now.getDate(),0,0,0)
              var nowts=nowtime.getTime()
           var ts=item.ts
            if(item.top){
              if(ts-nowts>=0&&ts-nowts-24*60*60*1000<=0){
                item.datetime="今天 "+item.datetime
              }else{
                if(ts-nowts-24*60*60*1000>0&&ts-nowts-2*24*60*60*1000<=0){
                  item.datetime="明天 "+item.datetime
                }
              }
              topplans.push(item)
            }else{
              if(ts-nowts>=0&&ts-nowts-24*60*60*1000<=0){
                todayplans.push(item)
              }else{
                if(ts-nowts-24*60*60*1000>0&&ts-nowts-2*24*60*60*1000)
                tomorrowplans.push(item)
              }
            }
          }
          var myplans=[]
          myplans.push(topplans)
          myplans.push(todayplans)
          myplans.push(tomorrowplans)
          this.setData({
           myplans:myplans,
           plancalendar:myplan
          })
},
async getmyactivity(){
 var activities=await axios.get('/activity/self/sign')
 console.log(activities)
  this.setData({
    activitycalendar:activities
  })
},
changemonthcalendaractive (e){
  var date=e.currentTarget.dataset.j
  this.setData({
    monthcalendardateactive: date,
    monthcalendarmonthactive: this.data.monthcalendarmonth
  })
  this.getmonthactivity()
},
async getmonthactivity(){
  console.log(this.data.monthcalendardateactive)
  var token=getApp().globalData.accessToken
  var user=getApp().globalData.user
  var monthstartdate=this.data.monthcalendaryear+"-"+(this.data.monthcalendarmonthactive+1)+"-"+this.data.monthcalendardateactive+" 00:00:00"
  var monthenddate=this.data.monthcalendaryear+"-"+(this.data.monthcalendarmonthactive+1)+"-"+this.data.monthcalendardateactive+" 24:00:00"
var monthresult= await axios.get('/activity?school='+user.school+"&campus="+this.data.selectregion+"&start="+monthstartdate+"&end="+monthenddate+"&flag=0&verified=1")
  monthresult.forEach(item=>{
    var startts=item.start
    var start=new Date(startts)
    var startstr=JSON.stringify(start).split("T")[1]
    var startarr=startstr.split(".")[0].split(":")
    if(start.getHours()<12){
      item.starttime=startarr[0]+":"+startarr[1]+"  AM"
    }else{
      item.starttime=startarr[0]+":"+startarr[1]+"  PM"
    }
    
    item.startdate=start.getMonth()+"."+start.getDate()
  })
  this.setData({
    mymonthactivities:monthresult
  })
  console.log("mymonthactivities",this.data.mymonthactivities)
},
async getweekactvity(){
  var user=getApp().globalData.user
  var startdate=this.data.calendaryear+"-"+(this.data.calendarmonth+1)+"-"+this.data.calendardates[0]+" 00:00:00"
  var enddate=this.data.calendaryear+"-"+(this.data.calendarmonth+1)+"-"+this.data.calendardates[6]+" 24:00:00"
  var url="/activity?school="+user.school+"&campus="+this.data.selectregion+"&start="+startdate+"&end="+enddate+"&flag=0&verified=1"
  var result=axios.get(url)
  
  this.setData({
    myactivities:result
  })
  var dates=this.data.calendardates
  var year=this.data.calendaryear
  var month=this.data.calendarmonth
  var activities=this.data.myactivities
  var weekactivities=[]
  for (let i = 0; i < dates.length; i++) {
    var startts=new Date(year,month,dates[i],8,0,0).getTime()
    var dateactivities=[]
    for (let j = 0; j < 7; j++) {
      var timeactivities=[]
      startts=startts+2*60*60*1000*(j)
      for (let k = 0; k < activities.length; k++) {
        var activity=activities[k]
        if(activity.start-startts>=0&&activity.start-startts-2*60*60*1000<=0){
          switch (activity.type){
            case "娱乐": timeactivities[2]=activity.id
            break
            case "交友": timeactivities[1]=activity.id
            break
            case "学习": timeactivities[0]=activity.id
            break
          }
        }
      }
      
      dateactivities.push(timeactivities)
    }
    weekactivities.push(dateactivities)
  }
  this.setData({
    weekactivities:weekactivities
  })
},
// daylyactivity:function(e){
//     var index=e.currentTarget.dataset.index
//     wx.navigateTo({
//       url:"../daylyactivity/daylyactivity?year="+this.data.nowyear+"&"+"month="+this.data.nowmonth+"&"+"day="+this.data.nowday+"&"+"selectregion="+this.data.selectregion
//     })
//   },
async changecalendartype(e){
    var index=e.detail.value
    this.setData({
      calendartype:this.data.calendartypes[index],
    })
  },
changedate:function(e){
    var num=JSON.parse(e.currentTarget.dataset.num)
    var starttime=new Date(this.data.calendaryear,this.data.calendarmonth,this.data.calendardates[0],0,0,0)
    var newstarttime=new Date()
    if(num==1){
       newstarttime=new Date(starttime.getTime()+7*24*60*60*1000)
    }else{
      newstarttime=new Date(starttime.getTime()-7*24*60*60*1000)
    }
    var calendardates=[]
    for (let i = 0; i < 7; i++) {
      calendardates.push(new Date(newstarttime.getTime()+i*24*60*60*1000).getDate())
    }
    this.setData({
      calendaryear:newstarttime.getFullYear(),
      calendarmonth:newstarttime.getMonth(),
      calendardates:calendardates
    })
    this.getweekactvity()
  },
  changecolor:function(e){
    var index=e.currentTarget.dataset.index
    this.setData({
      colorindex:index
    })
  },
changemonth(e){
    var monthcalendarmonth=0
    var num=JSON.parse(e.currentTarget.dataset.num)
    if(num<0&&this.data.monthcalendarmonth==0||num>0&&this.data.monthcalendarmonth==11){
      monthcalendarmonth=this.data.monthcalendarmonth
    }else{
      monthcalendarmonth=this.data.monthcalendarmonth+num
    }
    this.getdatebymonth(monthcalendarmonth,this.data.monthcalendaryear)
    this.getmonthactivity()
  },
async getdatebymonth(newstartmonth,newstartyear){
  var token=getApp().globalData.accessToken
  var user=getApp().globalData.user
  var monthlastdate=new Date(new Date(this.data.monthcalendaryear,this.data.monthcalendarmonth,1,0,0,0).getTime()-24*60*60*1000).getDate()
  var monthstartdate=this.data.monthcalendaryear+"-"+(this.data.monthcalendarmonth+1)+"-01 00:00:00"
  var monthenddate=this.data.monthcalendaryear+"-"+(this.data.monthcalendarmonth+1)+"-"+monthlastdate+" 24:00:00"
  var monthresult=await axios.get("/activity?school="+user.school+"&campus="+this.data.selectregion+"&start="+monthstartdate+"&end="+monthenddate+"&flag=0&verified=1")
    var starttime=new Date(newstartyear,newstartmonth+1,1,0,0,0)
    var monthcalendardate=[]
    var monthcalendaractivities=[]
    var firstdate=[]
    var date=1
    var monthcalendaractivity=[]
    for (let i = 0; i < 7; i++) {
      if(i<starttime.getDay()){
        firstdate.push(0)
        monthcalendaractivity.push([false,false,false])
      }else{
        firstdate.push(date)
        var startts=new Date(this.data.monthcalendaryear,this.data.monthcalendarmonth,
        date,0,0,0)
        var monthcalendaractivitychild=[]
        for (let l = 0; l < monthresult.length; l++) {
          const activity = monthresult[l];
          if(activity.start-startts>=0&&activity.start-24*60*60*1000-startts<0){
         
            switch(activity.type){
              case "学习":monthcalendaractivitychild[0]=true
              break
              case "交友":monthcalendaractivitychild[1]=true
              break
              case "娱乐":monthcalendaractivitychild[2]=true
            }
            
          }
        }
        monthcalendaractivity.push(monthcalendaractivitychild)
        date++;
      }
    }
    monthcalendaractivities.push(monthcalendaractivity)
    monthcalendardate.push(firstdate)
    var monthday=new Date(starttime.getTime()-24*60*60*1000).getDate()
   var tem=(monthday-date+2)/7

    for (let i = 0; i < tem-1; i++) {
      var monthcalendaractivity=[]
      var middledate=[]
      for (let j = 0; j < 7; j++) {
        middledate.push(date)
        var startts=new Date(this.data.monthcalendaryear,this.data.monthcalendarmonth,
          date,0,0,0)
          var monthcalendaractivitychild=[]
          for (let l = 0; l < monthresult.length; l++) {
            const activity = monthresult[l];
            if(activity.start-startts>=0&&activity.start-24*60*60*1000-startts<0){
              console.log("date",date)
              switch(activity.type){
                case "学习":monthcalendaractivitychild[0]=true
                break
                case "交友":monthcalendaractivitychild[1]=true
                break
                case "娱乐":monthcalendaractivitychild[2]=true
              }
              
            }
          }
          monthcalendaractivity.push(monthcalendaractivitychild)
        date++;
      }
      monthcalendaractivities.push(monthcalendaractivity)
      monthcalendardate.push(middledate)
    }
    var monthcalendaractivity=[]
      var enddate=[]
      tem=monthday-date+2
    for (let i = 0; i < tem-1; i++) {
      enddate.push(date)
      var startts=new Date(this.data.monthcalendaryear,this.data.monthcalendarmonth,
        date,0,0,0)
        var monthcalendaractivitychild=[]
        for (let l = 0; l < monthresult.length; l++) {
          const activity = monthresult[l];
          if(activity.start-startts>=0&&activity.start-24*60*60*1000-startts<0){
            switch(activity.type){
              case "学习":monthcalendaractivitychild[0]=true
              break
              case "交友":monthcalendaractivitychild[1]=true
              break
              case "娱乐":monthcalendaractivitychild[2]=false
            }
            
          }
        }
        monthcalendaractivity.push(monthcalendaractivitychild)
      date++;
    }
    monthcalendaractivities.push(monthcalendaractivity)
    monthcalendardate.push(enddate)
    console.log("monthcalendaractivities",monthcalendaractivities)
    this.setData({
      monthcalendardate:monthcalendardate,
      monthcalendarmonth:newstartmonth,
      monthcalendaractivities:monthcalendaractivities
    })
   
  },
changecalendar:function(e){
    var index=e.currentTarget.dataset.index
    this.setData({
      nowday:index
    })
    //获取活动数据并进行算法分析
  },
addactivity:function(e){
    var index=e.currentTarget.dataset.index
    var i=e.currentTarget.dataset.i
    var id=this.data.activities[i].id[index]
    var that=this
    wx.showModal({
      title:"确定加入个人计划吗",
      success:async function(res){
        if(res.confirm){
        var result=await axios.post('/activity/plan?activityId='+id,{})
          var activities=that.data.activities
          activities[i].title.splice(index,1)
          activities[i].id.splice(index,1)
          that.setData({
            activities:activities
          })
          wx.showToast({
            title:"成功加入个人计划"
          })
        }
      }
    })
  },
creatactivity(){
    wx.navigateTo({
    url:"../activityrelease/activityrelease"
    })
  },
async top(e){
    var id=e.currentTarget.dataset.id
    var type=e.currentTarget.dataset.type
    var top=type==0?false:true
   await axios.get("/plan/top?id="+id+"&isTop="+top)
   await this.getmyplan()
  },
async deleteplan(e){
  var id=e.currentTarget.dataset.id
  await axios.del('/plan?id='+id)
  await this.getmyplan()
  await this.getplanactivity()
},
 async changeregion(e){
    var value=e.detail.value
    this.setData({
      selectregion:this.data.region[value]
    })
    this.getweekactvity()
    this.getmonthactivity()
    this.getnowweekactivity()
  },
  async changetabbar(e){
    var index=e.currentTarget.dataset.index
    this.setData({
      currentindex:index
    })
  },
  creatplan:function(){
    wx.navigateTo({
      url:"../creatplan/creatplan"
    })
  },
  plandetail:function(e){
   var plantype=e.currentTarget.dataset.type;
   var planindex=e.currentTarget.dataset.index;
   var plandetail={}
    plandetail=this.data.myplans[plantype][planindex]
    wx.navigateTo({
      url:"../plandetail/plandetail?plandetail="+JSON.stringify(plandetail)
    })
  },
  changecalendaractivity(e){
    var date=e.currentTarget.dataset.date
    console.log(date)
    this.setData({
      monthcalendarmonth:this.data.calendarmonth,
      monthcalendarmonthactive:this.data.calendarmonth,
      monthcalendardateactive:date,
      calendartype:"月历",
      calendarindex:1
    })
    this.getdatebymonth(this.data.monthcalendarmonth,this.data.calendaryear)
    this.getmonthactivity()
  },
  async logininit(){
    var app=getApp()
      const {code:code}= await wx.p.login({})
      var baseUrl=axios.baseUrl
      var token=getApp().globalData.accessToken
      var res= await wx.p.request({
        url:baseUrl+"/accesstoken?code="+code,
        method:'POST',
        header:{
            'content-type': 'application/json'
        }
      })//请求模板
        var accessToken=res.data.accesstoken
        var user=res.data.user
         app.globalData.accessToken = accessToken;
        app.globalData.user=user;
         await wx.p.switchTab({
            url:"../calendar/calendar"
          })  
      
  },
  /**
   * 生命周期函数--监听页面显示
   */
 async onShow() {
  await this.logininit()
  await this.init()
  await this.getnowweekactivity()
  await this.getmyplan()
  await this.getdatebymonth(this.data.nowmonth,this.data.nowyear)
  await this.getweekactvity()
  await this.getmonthactivity()
   switch(this.data.currentindex){
     case 0:
    await this.getplanactivity()
     break
     case 1:this.getweekactvity()
    await this.getmonthactivity()
     break
   }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.init()
  this.getmyplan()
  this.getdatebymonth(this.data.nowmonth,this.data.nowyear)
  this.getweekactvity()
  this.getmonthactivity()
  wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})